<?php
require_once("init.php");
$g=$_GET['g'];
$g=my_url_decode($g);

$url=parse_url($g);
$temp=explode("/",$url['path']);
array_pop($temp);
define("BASEURL",$url['scheme']."://".$url['host'].implode("/",$temp)."/");
function proxifyURL($url) {
    if(strpos($url,"://")>0) {
        return "b.php?g=".my_url_encode($url);
    } else {
        return "b.php?g=".my_url_encode(BASEURL.$url);
    }
}

function html_attribute($input) {
    return str_replace($input[3], htmlspecialchars(proxifyURL(htmlspecialchars_decode($input[3]))), $input[0]);
}

$ch = curl_init($g);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT,"FireFox");
curl_setopt($ch, CURLOPT_REFERER,"I'm TinyTui2! See http://code.google.com/p/tinytui2/ ");

$data=curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http_code == 301 || $http_code == 302) {
    list($header) = explode("\r\n\r\n", $data, 2);
    $matches = array();
    preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
    $p = trim(array_pop($matches));
    header("Location: b.php?g=".my_url_encode($p));
} else {
    list($header) = explode("\r\n\r\n", $data, 2);
    $headers=explode("\r\n",$header);
    foreach($headers as $header_str) {
        if(stripos($header_str,":")>0) {
            if(strpos($header_str,"Content-Type:")>-1) {
                Header($header_str);
            }
            if(strpos($header_str,"Content-Length:")>-1) {
                Header($header_str);
            }
        }
    }
    $data=substr($data,strlen($header)+4);
    $data=preg_replace_callback('#(?><[A-Z][A-Z0-9]{0,15})(?>\s+[^>\s]+)*?\s*(?>(href|src|background)\s*=(?!\\\\)\s*)(?>([\\\'"])?)((?(2)(?(?<=")[^"]{1,1000}|[^\\\']{1,1000})|[^ >]{1,1000}))(?(2)\\2|)#i', 'html_attribute', $data);
    echo $data;
}
?>